package com.tsfyun.scm.controller.file;

import cn.hutool.core.io.FileUtil;
import com.tsfyun.common.base.controller.BaseController;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.scm.entity.file.ExportFile;
import com.tsfyun.scm.entity.file.UploadFile;
import com.tsfyun.scm.service.file.IExportFileService;
import com.tsfyun.scm.service.file.IUploadFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * 下载
 */
@Slf4j
@RestController
@RequestMapping(value = "/download")
public class DownloadController extends BaseController {

    @Autowired
    private IUploadFileService uploadFileService;

    @Autowired
    private IExportFileService exportFileService;

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 下载文件
     * @param request
     * @param response
     * @param fileId
     * @param down
     */
    @GetMapping(value = "/file/{fileId}")
    public void download(
            HttpServletRequest request, HttpServletResponse response,
            @PathVariable(value = "fileId",required = true)Long fileId,
            @RequestParam(value = "down",required = false,defaultValue = "")String down
    ){
        OutputStream outputStream = null;
        try{
            UploadFile uploadFile = uploadFileService.getById(fileId);
            TsfPreconditions.checkArgument(Objects.nonNull(uploadFile),new ServiceException("文件不存在"));
            File file = new File(uploadFile.getPath()+uploadFile.getNname());
            if(null != file && file.exists()){
                String contentType = "application/octet-stream";
                if(StringUtils.isEmpty(down)){
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    response.setHeader("Content-disposition","inline;filename=" + URLEncoder.encode(uploadFile.getName(), "UTF-8"));
                }else{
                    response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(uploadFile.getName(), "UTF-8"));
                }
                response.setContentType(contentType);
                outputStream = response.getOutputStream();
                FileUtil.writeToStream(file,outputStream);
                outputStream.flush();
            } else {
                throw new ServiceException("文件不存在");
            }
        } catch (Exception e){
            log.error("下载错误：",e);
        } finally {
            if(Objects.nonNull(outputStream)) {
                IOUtils.closeQuietly(outputStream);
            }
        }
    }

    //图片预览
    @GetMapping(value = "/img/{fileId}")
    public void img(@PathVariable(value = "fileId",required = true)Long fileId, HttpServletRequest request, HttpServletResponse response){
        OutputStream outputStream = null;
        try{
            UploadFile uploadFile = uploadFileService.getById(fileId);
            TsfPreconditions.checkArgument(Objects.nonNull(uploadFile),new ServiceException("文件不存在"));
            File file = new File(uploadFile.getPath()+uploadFile.getNname());
            if(null != file && file.exists()){
                response.setContentType(new MimetypesFileTypeMap().getContentType(file));
                response.setHeader("Content-disposition","inline;filename=" + URLEncoder.encode(uploadFile.getName(), "UTF-8"));
                outputStream = response.getOutputStream();
                FileUtil.writeToStream(file,outputStream);
                outputStream.flush();
            } else {
                throw new ServiceException("文件不存在");
            }
        }catch (Exception e){
            log.error("文件预览错误：",e);
        } finally {
            if(Objects.nonNull(outputStream)) {
                IOUtils.closeQuietly(outputStream);
            }
        }
    }


    /**
     * 下载文件
     * @param request
     * @param response
     * @param fileId
     * @param down
     */
    @GetMapping(value = "/predown/{fileId}")
    public void predown(
            HttpServletRequest request, HttpServletResponse response,
            @PathVariable(value = "fileId",required = true)Long fileId,
            @RequestParam(value = "down",required = false,defaultValue = "")String down
    ){
        OutputStream outputStream = null;
        try{
            ExportFile exportFile = exportFileService.getById(fileId);
            TsfPreconditions.checkArgument(Objects.nonNull(exportFile),new ServiceException("文件不存在"));
            File file = new File(exportFile.getPath());
            if(null != file && file.exists()){
                String contentType = "application/octet-stream";
                if(StringUtils.isEmpty(down)){
                    contentType = new MimetypesFileTypeMap().getContentType(file);
                    response.setHeader("Content-disposition","inline;filename=" + URLEncoder.encode(exportFile.getFileName(), "UTF-8"));
                }else{
                    response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(exportFile.getFileName(), "UTF-8"));
                }
                response.setContentType(contentType);
                outputStream = response.getOutputStream();
                FileUtil.writeToStream(file,outputStream);
                outputStream.flush();

                if(exportFile.getOnce()) {
                    //启动子线程删除文件
                    threadPoolTaskExecutor.execute(()->{
                        //exportFileService.removeExportFile(fileId,exportFile.getPath());
                    });
                }
            } else {
                throw new ServiceException("文件不存在");
            }
        } catch (Exception e){
            log.error("下载错误：",e);
        } finally {
            if(Objects.nonNull(outputStream)) {
                IOUtils.closeQuietly(outputStream);
            }
        }
    }

}
